import torch
from torch import nn
import math
import torch.nn.functional as F
#需要分类的类别数
classes=100

fidx_u_16 = [0,0,6,0,0,1,1,4,5,1,3,0,0,0,2,3] # 论文所选频率的水平指数
fidx_v_16 = [0,1,0,5,2,0,2,0,0,6,0,4,6,3,2,5] # 论文所选频率的垂直指数
# 获取一维通道的DCT
# L为输入的长度
def get_1d_dct(pos, freq, L):
    result = math.cos(math.pi * freq * (pos + 0.5) / L) / math.sqrt(L)
    if freq == 0:
        return result
    else:
        return result * math.sqrt(2)

# 推广到二维DCT
def get_dct_weights(input_width, input_height, input_channel, fidx_u= fidx_u_16, fidx_v= fidx_v_16):
    # 论文将频率空间分为7*7,实验结果表明,[u,v]=[0,0],即GAP的效果最好(乐),当然了，改进的点在于在信道注意力中使用多个频率分量
    # 使不同大小的频率与 7x7 频率空间相同
    fidx_horizon = [u*(input_width//7) for u in fidx_u]
    fidx_vertical = [v*(input_height//7) for v in fidx_v]
    dct_weights = torch.zeros(1, input_channel, input_width, input_height)
    c_part = input_channel // len(fidx_horizon)
    # 拆分通道
    for i, (u_x, v_y) in enumerate(zip(fidx_horizon, fidx_vertical)):
        for t_x in range(input_width):
            for t_y in range(input_height):
                dct_weights[:, i * c_part: (i+1)*c_part, t_x, t_y]\
                =get_1d_dct(t_x, u_x, input_width) * get_1d_dct(t_y, v_y, input_height)

    return dct_weights

# SE-Block单元--SEblock是一个子结构，几乎可以嵌入任何一个神经网络模型之中
class FcaBlock(nn.Module):
    def __init__(self, input_channel, width, height, reduction=16):
        super(FcaBlock, self).__init__()
        self.width = width
        self.height = height


        # self.adaptive_avg_pool = nn.AdaptiveAvgPool2d(1)  # 全局自适应池化
        self.register_buffer('pre_computed_dct_weights', get_dct_weights(self.width, self.height, input_channel))
        self.fc = nn.Sequential(
            nn.Linear(input_channel, input_channel // reduction),
            nn.ReLU(inplace=True),
            nn.Linear(input_channel // reduction, input_channel),
            nn.Sigmoid()
        )

    def forward(self, x):
        b, c, h, w = x.size()

        # squeeze操作:(b,c,h,w)->(b,c)
        #y = self.adaptive_avg_pool(x).view(b, c)
        y = F.adaptive_avg_pool2d(x, (self.height, self.width))
        y = torch.sum(y*self.pre_computed_dct_weights, dim=[2,3])

        # FC获取通道注意力权重，是具有全局信息的
        y = self.fc(y).view(b, c, 1, 1)

        # 注意力作用每一个通道上
        y = x * y.expand_as(x)
        # 残差连接
        return x+y




class Res2NetBottleneck(nn.Module):
    expansion = 4  #残差块的输出通道数=输入通道数*expansion
    def __init__(self, inplanes, planes, downsample=None, stride=1, scales=4, groups=1, width=32,height=32,reduction=16, norm_layer=True):
        #scales为残差块中使用分层的特征组数，groups表示其中3*3卷积层数量，SE模块和BN层
        super(Res2NetBottleneck, self).__init__()

        if planes % scales != 0: #输出通道数为4的倍数
            raise ValueError('Planes must be divisible by scales')
        if norm_layer:  #BN层
            norm_layer = nn.BatchNorm2d

        bottleneck_planes = groups * planes
        self.scales = scales
        self.stride = stride
        self.downsample = downsample
        #1*1的卷积层,在第二个layer时缩小图片尺寸
        self.conv1 = nn.Conv2d(inplanes, bottleneck_planes, kernel_size=1, stride=stride)
        self.bn1 = norm_layer(bottleneck_planes)
        #3*3的卷积层，一共有3个卷积层和3个BN层
        self.conv2 = nn.ModuleList([nn.Conv2d(bottleneck_planes // scales, bottleneck_planes // scales,
                                              kernel_size=3, stride=1, padding=1, groups=groups) for _ in range(scales-1)])
        self.bn2 = nn.ModuleList([norm_layer(bottleneck_planes // scales) for _ in range(scales-1)])
        #1*1的卷积层，经过这个卷积层之后输出的通道数变成
        self.conv3 = nn.Conv2d(bottleneck_planes, planes * self.expansion, kernel_size=1, stride=1)
        self.bn3 = norm_layer(planes * self.expansion)
        self.relu = nn.ReLU(inplace=True)

        # self.se = SEModule(planes * self.expansion) if se else None
        self.fca = FcaBlock(planes * self.expansion, width, height, reduction)


    def forward(self, x):
        identity = x

        #1*1的卷积层
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        #scales个(3x3)的残差分层架构
        xs = torch.chunk(out, self.scales, 1) #将x分割成scales块
        ys = []
        for s in range(self.scales):
            if s == 0:
                ys.append(xs[s])
            elif s == 1:
                ys.append(self.relu(self.bn2[s-1](self.conv2[s-1](xs[s]))))
            else:
                ys.append(self.relu(self.bn2[s-1](self.conv2[s-1](xs[s] + ys[-1]))))
        out = torch.cat(ys, 1)

        #1*1的卷积层
        out = self.conv3(out)
        out = self.bn3(out)


        out = self.fca(out)
        #下采样
        if self.downsample:
            identity = self.downsample(identity)

        out += identity
        out = self.relu(out)

        return out

class FcaRes2Net(nn.Module):
    def __init__(self, block, layers, num_classes=100, width=32, scales=4, groups=1,
                 zero_init_residual=True, se=True, norm_layer=True):
        super(FcaRes2Net, self).__init__()
        if norm_layer:  #BN层
            norm_layer = nn.BatchNorm2d
        #通道数分别为64,128,256,512
        planes = [int(width * scales * 2 ** i) for i in range(4)]
        self.inplanes = planes[0]

        #7*7的卷积层，3*3的最大池化层
        self.conv1 = nn.Conv2d(3, planes[0], kernel_size=7, stride=2, padding=3,
                               bias=False)
        self.bn1 = norm_layer(planes[0])
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        #四个残差块
        self.layer1 = self._make_layer(block, planes[0], layers[0], stride=1, scales=scales, groups=groups, norm_layer=norm_layer)
        self.layer2 = self._make_layer(block, planes[1], layers[1], stride=2, scales=scales, groups=groups, norm_layer=norm_layer)
        self.layer3 = self._make_layer(block, planes[2], layers[2], stride=2, scales=scales, groups=groups, norm_layer=norm_layer)
        self.layer4 = self._make_layer(block, planes[3], layers[3], stride=2, scales=scales, groups=groups, norm_layer=norm_layer)
        #自适应平均池化，全连接层
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(planes[3] * Res2NetBottleneck.expansion, num_classes)

        #初始化
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
        #零初始化每个剩余分支中的最后一个BN，以便剩余分支从零开始，并且每个剩余块的行为类似于一个恒等式
        if zero_init_residual:
            for m in self.modules():
                if isinstance(m, Res2NetBottleneck):
                    nn.init.constant_(m.bn3.weight, 0)

    def _make_layer(self, block, planes, blocks, stride=1, scales=4, groups=1, width=32,height=32,reduction=16, norm_layer=True):
        if norm_layer:
            norm_layer = nn.BatchNorm2d

        downsample = None  #下采样，可缩小图片尺寸
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride),
                norm_layer(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, downsample, stride=stride, scales=scales, groups=groups, width=width,height=height,reduction=reduction, norm_layer=norm_layer))
        self.inplanes = planes * block.expansion
        for _ in range(1, blocks):
            layers.append(block(self.inplanes, planes, scales=scales, groups=groups, width=width,height=height,reduction=reduction, norm_layer=norm_layer))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = x.view(x.size(0), -1)
        logits = self.fc(x)
        probas = nn.functional.softmax(logits, dim=1)

        return probas
